package util

import (
	"context"
	"encoding/json"
	"fmt"
	"gin_reptile/model"
	. "gin_reptile/pkg/global"
	"github.com/golang-module/carbon/v2"
	"github.com/spf13/cast"
	"io"
	"net/http"
)

type ApiVo struct {
	Code int     `json:"code"`
	Msg  string  `json:"msg"`
	Data ApiData `json:"data"`
}

type ApiData struct {
	Currency string      `json:"currency"`
	Name     string      `json:"name"`
	List     interface{} `json:"list"`
}

type Values struct {
	Name       string `json:"name"`
	Rate       string `json:"rate"`
	UpdateTime string `json:"updatetime"`
}

func GetCurrencyApiData() {
	fmt.Printf("当前时间为：%s", carbon.Now().ToDateTimeString())
	var (
		url      = Viper.GetString("api.url")
		body     []byte
		jsonByte []byte
		err      error
	)
	ctx := context.TODO()

	// 发送GET请求获取网页内容
	resp, err := http.Get(url)
	if err != nil {
		Logger.Error(ctx, err)
	}
	defer resp.Body.Close()

	// 检查请求是否成功
	if resp.StatusCode != 200 {
		Logger.Errorf(ctx, "无法获取API数据，状态码：%d", resp.StatusCode)
	}

	body, err = io.ReadAll(resp.Body)
	if err != nil {
		Logger.Error(ctx, err)
	}
	apiVo := &ApiVo{}
	err = json.Unmarshal(body, apiVo)
	if err != nil || apiVo.Code != 1 {
		Logger.Error(ctx, err)
	}
	jsonByte, err = json.Marshal(apiVo.Data.List)
	if err != nil {
		Logger.Error(ctx, err)
	}
	apiList := map[string]Values{}
	if err = json.Unmarshal(jsonByte, &apiList); err != nil {
		Logger.Error(ctx, err)
	}

	if len(apiList) > 0 {
		rateDb := make([]model.IfcgateRate, 0)
		for currency, valueObj := range apiList {
			rateDb = append(rateDb, model.IfcgateRate{
				Currency: currency,
				Rate:     cast.ToFloat64(valueObj.Rate),
				Name:     valueObj.Name,
			})
		}
		if _, err = Gdb.Model("ifcgate_rate").Data(rateDb).Batch(len(rateDb)).Save(); err != nil {
			Logger.Error(ctx, err)
		}
	}
}
